package com.zm.rpc.server;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zm.rpc.server.cfg.RpcServerCfg;
import com.zm.rpc.server.channel.RpcServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

@Service
public class RpcServer {
    private static final Logger log = Logger.getLogger(RpcServer.class);
    
    @Autowired
    private RpcServerCfg rpcServerCfg;

    @Autowired
    private RpcServerChannelInitializer rpcServerChannelInitializer;
    
    public RpcServer() {
    }


    public void start(){
        log.info("RPC Server start!");
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap server = new ServerBootstrap();
       
        try{
            server.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(rpcServerChannelInitializer);
                    }
                    
                })
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.SO_BACKLOG, 1024);
            
            ChannelFuture future = server.bind(rpcServerCfg.getHost(), rpcServerCfg.getPort());
            future.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture ch) throws Exception {
                    if(ch.isSuccess()){
                        log.info(String.format("RPC Server start SUCCEED![Host:%s Port:%d]",rpcServerCfg.getHost(), rpcServerCfg.getPort()));
                    }else{
                        log.error("RPC Server start FAILD!");
                    }
                }
                
            });
            future.channel().closeFuture().sync();
                
        }catch(Exception e){
            log.error("RPC Server start error!",e);
        }
    }

    
}
